from pathlib import Path

import loguru
from PySide6.QtWidgets import QApplication, QFileDialog

from src.core.enums import ProgramsStatus
from src.main_model import MainModel
from src.main_view import MainView
from src.utils.run_in_thread import RunInThread


class MainPresenter:
    def __init__(self):
        self._view = MainView()
        self._model = MainModel()

        self._connect_signal()

    @property
    def view(self):
        return self._view

    @property
    def model(self):
        return self._model

    def show(self):
        self._view.show()

    def _start(self):
        lineedit_text = self._view.get_select_file_lineedit().text()
        if not lineedit_text:
            loguru.logger.warning("未选择文件")
            return

        input_file_path: Path = Path(lineedit_text)
        if not input_file_path.exists():
            loguru.logger.warning(f"文件{input_file_path}不存在")
            return

        def start_func():
            self._view.status = ProgramsStatus.Running.value
            self._model.decrypted(input_file_path)

        def finished_func():
            self._view.get_status_lb().setText("解锁完成")
            self._view.status = ProgramsStatus.Finish.value

        self._run_in_thread = RunInThread()
        self._run_in_thread.set_start_func(start_func)
        self._run_in_thread.set_finished_func(finished_func)
        self._run_in_thread.start()

    def _select_file(self):
        # 打开文件选择对话框(文件后缀名为.vmd或者.pmx)
        file_path, _ = QFileDialog.getOpenFileName(
            self._view, "选择文件", "", "VMD文件(*.vmd);;PMX文件(*.pmx)"
        )
        if not file_path:
            loguru.logger.warning("未选择文件")
            self._view.status = ProgramsStatus.UnSelectFile.value
            self._view.get_select_file_lineedit().clear()
            return

        self._view.get_select_file_lineedit().setText(file_path)
        self._view.status = ProgramsStatus.SelectFile.value

    def _connect_signal(self):
        self._view.get_select_file_btn().clicked.connect(self._select_file)
        self._view.get_start_btn().clicked.connect(self._start)


if __name__ == '__main__':
    app = QApplication([])
    presenter = MainPresenter()
    presenter.show()
    app.exec()
